package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.FEED_KEY;


@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    @Resource
    private IFollowService followService;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    /**
     * 分页查询Blog
     * */
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = this.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.queryIsLike(blog);
        });
        return Result.ok(records);
    }

    @Override
    /**
     * 根据id查询Blog
     * */
    public Result queryBlogById(Long id) {
        // 1.查询 blog
        Blog blog = this.getById(id);
        if (blog == null){
            log.error("笔记不存在!"+id);
            return Result.fail("笔记不存在!");
        }
        // 2.查询笔记作者用户
        this.queryBlogUser(blog);
        // 3.查询笔记是否被当前用户点赞
        this.queryIsLike(blog);

        return Result.ok(blog);
    }

    @Override
    /**
     * 登录用户点赞笔记
     * */
    public Result likeBlog(Long id) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();

        // 查看用户是否已点赞
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        // 从 sortedset 集合判断分数是否存在判断用户是否点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

        // 未点赞
        if (score == null){
            // 数据库点赞数+1
            boolean isSuccess = this.update().setSql("liked = liked + 1").eq("id", id).update();
            // 保存登录用户 id 进 redis
            if (isSuccess){
                // zadd key value score
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }else {
            // 已点赞
            // 数据库点赞数-1
            boolean isSuccess = this.update().setSql("liked = liked - 1").eq("id", id).update();
            // 在 redis 删除登录用户 id
            if (isSuccess){
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        }

        return Result.ok();
    }

    @Override
    /**
     * 查询笔记的点赞排行榜前5的用户
     * */
    public Result likesBlog(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;

        // 1.查询redis sortedset 的前5 zrange key 0 4
        Set<String> range = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (range == null || range.isEmpty()){
            return Result.ok(Collections.emptyList());
        }

        // 2.解析排行榜前几的用户 id 数据
        List<Long> ids = range.stream().map(Long::valueOf).collect(Collectors.toList());

        // 3.根据用户id查询用户 WHERE id IN ( 5 , 1 ) ORDER BY FIELD(id, 5, 1)
        String idStr = StrUtil.join(",", ids);
        List<UserDTO> userDTOS = userService.query()
                .in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());

        // 4.返回数据
        return Result.ok(userDTOS);
    }

    /**
     * 查询笔记的作者用户
     * */
    public void queryBlogUser(Blog blog){
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 查询笔记是否被当前登录用户点赞
     * */
    public void queryIsLike(Blog blog){
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            // 用户未登录，无需查询是否点赞
            return;
        }
        // 查询 redis 的 sortedset 是否存在当前用户
        Long userId = user.getId();
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
        // 存在则已点赞
        // 不存在则未点赞
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
//        Boolean isMember = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
//        blog.setIsLike(BooleanUtil.isTrue(isMember));
        blog.setIsLike(score != null);
    }

    /**
     * 保存笔记，并推送给粉丝的收件箱
     * */
    @Override
    public String saveBlog(Blog blog) {
        // 1.获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 2.保存探店笔记到数据库
        boolean isSuccess = this.save(blog);
        String blogId = blog.getId().toString();
        if (isSuccess){
            // 3.查询笔记作者所有粉丝 id
            List<Follow> ids = followService.query().eq("follow_user_id", user.getId()).list();
            // 4.推送笔记 id 到粉丝的收件箱
            for (Follow follow : ids) {
                // 4.1 获取粉丝 id
                String key = FEED_KEY + follow.getUserId();
                // 4.2 推送
                stringRedisTemplate.opsForZSet().add(key, blogId, System.currentTimeMillis());
            }
        }
        // 5.返回笔记 id
        return blogId;
    }

    /**
     * 滚动分页查询关注的博主们发布的笔记
     * */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 1.获取当前用户 id
        Long userId = UserHolder.getUser().getId();

        // 2.滚动分页查询当前用户收件箱的笔记 id
        String key = FEED_KEY + userId;
        // ZREVRANGEBYSCORE key Max Min LIMIT offset count
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet()
                        .reverseRangeByScoreWithScores(key, max, 0, offset, 2);
        // 3.非空判断
        if (typedTuples == null || typedTuples.isEmpty()){
            return Result.ok();
        }

        // 4.解析数据：blogId、minTime（时间戳）、offset
        ArrayList<Blog> blogList = new ArrayList<>(typedTuples.size());
        long minTime = 0;
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple: typedTuples) {
            // 4.1根据笔记 id 查询笔记信息
            String blogId = tuple.getValue();
            Blog blog = this.getById(Long.valueOf(blogId));
            // 4.1.1查询笔记作者用户
            this.queryBlogUser(blog);
            // 4.1.2查询笔记是否被当前用户点赞
            this.queryIsLike(blog);
            blogList.add(blog);

            // 4.2获取时间戳
            long time = tuple.getScore().longValue();
            if (time != minTime){
                minTime = time;
                os = 1;
            }else {
                os++;
            }
        }

        // 下面这条语句应该没必要
//        os = minTime == max? os : os+offset;

        ScrollResult r = new ScrollResult();
        r.setList(blogList);
        r.setOffset(os);
        r.setMinTime(minTime);

        return Result.ok(r);
    }


}
